import PlayerController from "./PlayerController";
import RayCastType = cc.RayCastType;

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property (Number)
    radius: number = 1000;

    ctx: cc.Graphics = null;

    playerController: PlayerController = null;

    onLoad () {
        this.ctx = this.getComponent(cc.Graphics);
        this.playerController = cc.find("Canvas").getComponent("PlayerController");

    }


    update () {
        let direction = this.playerController.direction;
        let position2 = cc.pMult(direction,this.radius);
        let manager = cc.director.getPhysicsManager();
        var results = manager.rayCast(direction,position2,RayCastType.All);

        this.ctx.clear();
        if (results[0]) {
            position2 = results[0].point;
        }

        results.forEach(result => {
            this.ctx.circle(result.point.x, result.point.y, 15);
        });

        this.ctx.fill();

        this.ctx.moveTo(direction.x, direction.y);
        this.ctx.lineTo(position2.x, position2.y);
        this.ctx.stroke();

    }


    // 只在两个碰撞体开始接触时被调用一次
    onBeginContact (contact: cc.PhysicsContact, selfCollider: cc.PhysicsCollider, otherCollider: cc.PhysicsCollider) {
        console.log("碰撞开始了");
        if (otherCollider.body.node.group == "platform") {
            this.playerController.direction = cc.pNeg(this.playerController.direction);
        }

        if (otherCollider.body.node.group == "enemy") {
            let worldManifold = contact.getWorldManifold();
            let points = worldManifold.points;

            let body = otherCollider.body;
            body.linearVelocity = cc.v2();
            selfCollider.body.linearVelocity = cc.v2();
            body.applyLinearImpulse(cc.pMult(this.playerController.direction,100), body.getLocalCenter(), true);
            selfCollider.body.applyLinearImpulse(cc.pMult(this.playerController.direction,50).negSelf(), selfCollider.body.getLocalCenter(), true);
        }

    }

    onPreSolve (contact: cc.PhysicsContact, selfCollider: cc.PhysicsCollider,otherCollider: cc.PhysicsCollider) {


    }




}
